// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
// eslint-disable-next-line no-extend-native
Date.prototype.Format = function(fmt) {
  var o = {
    'M+': this.getMonth() + 1, // 月份
    'd+': this.getDate(), // 日
    'h+': this.getHours(), // 小时
    'm+': this.getMinutes(), // 分
    's+': this.getSeconds(), // 秒
    'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
    'S': this.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length)) }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) }
  }
  return fmt
}

export function formatTimeToStr(times, pattern) {
  var d = new Date(times).Format('yyyy-MM-dd hh:mm:ss')
  if (pattern) {
    d = new Date(times).Format(pattern)
  }
  return d.toLocaleString()
}

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/')
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// 表单重置
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields()
  }
}

// 添加日期范围
export function addDateRange(params, dateRange) {
  var search = params
  search.beginTime = ''
  search.endTime = ''
  if (dateRange != null && dateRange != '') {
    search.beginTime = this.dateRange[0]
    search.endTime = this.dateRange[1]
  }
  return search
}

// 回显数据字典
export function selectDictLabel(datas, value) {
  var actions = []
  Object.keys(datas).map((key) => {
    if (datas[key].key === ('' + value)) {
      actions.push(datas[key].value)
      return false
    }
  })
  return actions.join('')
}

// 字符串格式化(%s )
export function sprintf(str) {
  var args = arguments
  var flag = true
  var i = 1
  str = str.replace(/%s/g, function() {
    var arg = args[i++]
    if (typeof arg === 'undefined') {
      flag = false
      return ''
    }
    return arg
  })
  return flag ? str : ''
}

// 转换字符串，undefined,null等转化为""
export function praseStrEmpty(str) {
  if (!str || str === 'undefined' || str === 'null') {
    return ''
  }
  return str
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 * @param {*} rootId 根Id 默认 0
 */
export function handleTree(data, id, parentId, children, rootId) {
  id = id || 'id'
  parentId = parentId || 'parentId'
  children = children || 'children'
  rootId = rootId || 0
  // 对源数据深度克隆
  const cloneData = JSON.parse(JSON.stringify(data))
  // 循环所有项
  const treeData = cloneData.filter(father => {
    const branchArr = cloneData.filter(child => {
      // 返回每一项的子级数组
      return father[id] === child[parentId]
    })
    branchArr.length > 0 ? father.children = branchArr : ''
    // 返回第一层
    return father[parentId] === rootId
  })
  return treeData !== '' ? treeData : data
}

// 时间戳转年月日
export function dateFormat(format, time) {
  if (!time) {
    return ''
  }
  var t = new Date(time)
  var tf = function(i) {
    return (i < 10 ? '0' : '') + i
  }
  return format.replace(/yyyy|mm|dd|HH|MM|SS/g, function(a) {
    switch (a) {
      case 'yyyy':
        return tf(t.getFullYear())
      case 'mm':
        return tf(t.getMonth() + 1)
      case 'dd':
        return tf(t.getDate())
      case 'HH':
        return tf(t.getHours())
      case 'MM':
        return tf(t.getMinutes())
      case 'SS':
        return tf(t.getSeconds())
    }
  })
}

// el-paicker时间转化
export function conversionTime(date) {
  let start, end, timeDate

  // 闰年
  function leap(year) {
    return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)
  }

  // 开始时间
  const now = new Date(date[0])
  const year = now.getFullYear()
  let month = now.getMonth() + 1
  let day = now.getDate()
  month = (month < 10 ? '0' + month : month)
  day = (day < 10 ? '0' + day : day)
  start = (year.toString() + '-' + month.toString() + '-' + day.toString())
  // 结束时间
  const oldNow = new Date(date[1])
  let oldYear = oldNow.getFullYear()
  const oldMonth = oldNow.getMonth() + 1
  let oldDay = oldNow.getDate() + 1
  oldDay = (oldDay < 10 ? '0' + oldDay : oldDay)
  // debugger
  if (oldMonth === 2 && !leap(oldYear)) {
    if (oldDay < 29) {
      end = (oldYear.toString() + '-' + oldMonth.toString() + '-' + oldDay.toString())
    } else {
      let ste = oldMonth + 1
      ste = (ste < 10 ? '0' + ste : ste)
      end = (oldYear.toString() + '-' + ste.toString() + '-' + '01')
    }
  } else if ([1, 3, 5, 7, 8, 10].findIndex(a => a === oldMonth) !== -1 && !leap(oldYear)) {
    if (oldDay < 32) {
      end = (oldYear.toString() + '-' + oldMonth.toString() + '-' + oldDay.toString())
    } else {
      let ste = oldMonth + 1
      ste = (ste < 10 ? '0' + ste : ste)
      end = (oldYear.toString() + '-' + ste.toString() + '-' + '01')
    }
  } else if ([12].findIndex(a => a === oldMonth) !== -1) {
    if (oldDay < 32) {
      end = (oldYear.toString() + '-' + oldMonth.toString() + '-' + oldDay.toString())
    } else {
      oldYear = oldYear + 1
      end = (oldYear.toString() + '-' + '01' + '-' + '01')
    }
  } else if ([4, 6, 9, 11].findIndex(a => a === oldMonth) !== -1 && !leap(oldYear)) {
    if (oldDay < 31) {
      end = (oldYear.toString() + '-' + oldMonth.toString() + '-' + oldDay.toString())
    } else {
      let ste = oldMonth + 1
      ste = (ste < 10 ? '0' + ste : ste)
      end = (oldYear.toString() + '-' + ste.toString() + '-' + '01')
    }
  } else if (oldMonth === 2 && leap(oldYear)) {
    if (oldDay < 30) {
      end = (oldYear.toString() + '-' + oldMonth.toString() + '-' + oldDay.toString())
    } else {
      let ste = oldMonth + 1
      ste = (ste < 10 ? '0' + ste : ste)
      end = (oldYear.toString() + '-' + ste.toString() + '-' + '01')
    }
  }
  timeDate = [start, end]
  return timeDate
}
